$(document).ready(function(){
    $(function(){
        $(".search-box input").focus(function(){
            $(this).parent('div').css('border','1px solid #F5C63E');
        }).blur(function(){
            $(this).parent('div').css('border','1px solid #C0C0C0');
        });
    });
    //调用日期选择插件
    $('#datePicker').fdatepicker({
    	format:'yyyy-mm-dd',
    });;
    //发票方式单选
    $(".status").on("click",function(){
        $(this).addClass("on").siblings().removeClass("on");
    });
  //备注相关
    //    var remark=$('table tbody tr td:nth-child(7) p');
    $($('table tbody tr td:nth-child(7) p')).each(function(){
        if($(this).html()==""){
            $(this).parent().addClass('add');
        }else{
            $(this).parent().addClass('reverse');
        }
    });
    $('table').on('click','tbody tr td:nth-child(7)',function(){
        remark=$(this).children('p');
        if($(this).hasClass('add')){
            $('.mask-box').css('display','block');
            $('#remark-text').val(remark.html());
        }else if($(this).hasClass('reverse')){
            $('.mask-box').css('display','block').find('h3').html('修改商品备注');
            $('#remark-text').val(remark.html());
        };
    });
    $('.save').on('click',function(){
        var msg=$('#remark-text').val();
        if($.trim(msg)!=""){
            remark.html(msg);
            $('.mask-box').css('display','none');
            remark.parent().removeClass('add').addClass('reverse');
        }else{
            remark.html("");
            $('.mask-box').css('display','none');
            remark.parent().removeClass('reverse').addClass('add');
        }
    });
    $('.cancel').on('click',function(){
        $('.mask-box').css('display','none');
    });
//是否特价
    $('.speical-price P:nth-child(2) s').click(function(){
    	$(this).toggleClass('active');
    	$(this).hasClass('active')?$(this).siblings('input').attr('readonly',false):$(this).siblings('input').attr('readonly',true);
    	if($(this).hasClass('active')){
    		//设置特批价格
    		$('.speical-price input').on('keyup',function(){
    			$('.settle-accounts').children('.price').children('p:nth-child(2)').children('span').children('span').html($(this).val());
    			$('.settle-accounts').children('.price').children('p:nth-child(3)').children('span').children('span').html($(this).val());
    		})
    	}else{
    		$(this).siblings('input').val('');
    		$('.settle-accounts').children('.price').children('p:nth-child(2)').children('span').children('span').html('0.00');
			$('.settle-accounts').children('.price').children('p:nth-child(3)').children('span').children('span').html($('.settle-accounts').children('.price').children('p:nth-child(1)').children('span').children('span').html());
    	}
    });
  //省市2级联动菜单
    $(".address-msg .address-box .province input").click(function(){
        var input=$(this);
        var ul=$(this).siblings('ul');
        $.ajax({
        	type:'get',
        	url:'/DistributorSystem/product/findAllProvinces',
        	data:{},
        	success:function(data){
        		var html="";
        		var provinceList=JSON.parse(data).provinces;
        		for(var i=0;i<provinceList.length;i++){
        			html+="<li data-id="+provinceList[i].id+">"+provinceList[i].name+"</li>";
        		}
        		$(ul).html(html).removeClass('hide');
        	},
        	error:function(){
        	}
        });
    });
    var province="";
    $(".province").on('click','li',function(){
    	province=$(this).html();
        var provinceId=$(this).attr('data-id');
        var city_block=$(this).parent().parent().siblings('.city').children('ul');
        //市
        $.ajax({
        	type:'get',
        	url:'/DistributorSystem/product/findAllCitys?id='+provinceId,
        	data:{},
        	success:function(data){
        		var html="";
        		var cityList=JSON.parse(data).citys;
        		for(var i=0;i<cityList.length;i++){
        			html+="<li data-id="+cityList[i].id+">"+cityList[i].name+"</li>";
        		}
        		$(city_block).html(html);
        	},
        	error:function(){
        		
        	}
        })
    });
    $(".city").on('click','li',function(event){
        var city=$(this).html();
        var id=$(this).attr('data-id');
        event.stopPropagation();
        $(this).parent().addClass('hide')
        $(this).parent().siblings('input').val(city).attr('data-id',id);
    });
  //客户名称搜索输入框模糊查询
    $('.top-block').on('keyup','.search-box input',function(){
    	var keyWords=$(this).val();
    	var ul=$('.search-box').children('ul');
    	if($.trim(keyWords)!=""){
    		var html="";
    		$.ajax({
    			type:"POST",
    			url:"/DistributorSystem/customer/findCustomersByKey",
    			data:{"key":keyWords},
    			success:function(data){
    				var list = JSON.parse(data).customers;
    					if(list.length>0){
    						var name=list[0].name;
    	    				var id=list[0].id;
    						ul.css('display','block');
    						for(var i=0;i<list.length;i++){
    							html+="<li data-id="+id+">"+name+"</li>"
    						}
    						ul.html(html);
    					}else{
    						ul.css('display','none');
    					}
    			}
    		});
    	}else{
    		ul.css('display','none');
    	}
    });
    $('.top-block').on('click','.search-box ul li',function(){
    	$('.search-box').children('input:nth-child(1)').val($(this).html());
    	$('.search-box').children('input:nth-child(2)').val($(this).attr('data-id'));
    	$('.search-box').children('ul').css('display','none');
    	$.ajax({
    		type:"POST",
			url:"/DistributorSystem/customer/findCustomerDeliveryAddressById",
			data:{"id":$(this).attr('data-id')},
			success:function(data){
				var addr = JSON.parse(data).customersDeliveryAddress;
				$('.take').children('input:nth-child(3)').val(addr.consignee);
				$('.take').children('input:nth-child(5)').val(addr.mobile);
				$('.take').children('div:nth-child(7)').children('input:nth-child(3)').val(addr.province+addr.city+addr.address);
				$('.take').children('div:nth-child(7)').children('div:nth-child(2)').children('input').attr('data-id',addr.cityId);
				$('.take').children('div:nth-child(7)').children('div:nth-child(2)').children('input').val(addr.city);
				$('.take').children('div:nth-child(7)').children('div:nth-child(1)').children('input').val(addr.province);
			}
    	});
    });
  //添加商品输入框模糊查询
    $('.top-block').on('keyup','.product-search-box input',function(){
    	var keyWords=$(this).val();
    	var distributorId=$(this).parent().siblings('div').children('.hide').val();
    	var ul=$(this).siblings('ul');
    	search(keyWords,distributorId,ul);
    });
    function search(keyWords,distributorId,ul){
    	var html="";
    	if($.trim(keyWords)!=""){
    		$.ajax({
    			type:"POST",
    			url:"/DistributorSystem/product/findProductByKey",
    			data:{"key":keyWords,"distributorId":distributorId},
    			success:function(data){
    					if(data.length>0){
    						ul.css('display','block');
    						for(var i=0;i<data.length;i++){
    							html+="<li data-id="+data[i].id+">"+data[i].name+"<span>"+data[i].specNameValue+"</span></li>"
    						}
    						ul.html(html);
    					}else{
    						ul.css('display','none');
    					}
    			}
    		});
    	}else{
    		ul.css('display','none');
    	}
    };
    $('.top-block').on('click','.product-search-box ul li',function(){
    	$('.product-search-box').children('input').val($(this).text());
    	$(this).parent().css('display','none');
    	var name=$(this).children('span:nth-child(1)').html();
    	var id = $(this).attr('data-id');
    	var tbody =$(this).parent().parent().parent().siblings('table').children('tbody');
    	$.ajax({
    		type:"GET",
    		url:"/DistributorSystem/product/findProductInfoById",
    		data:{"id":id},
    		success:function(data){
    			var html="";
    			html+= "<tr data-id='"+data.productId+"' data-isActivity='0'>"
                +"<td width='5%'><s></s></td>"
                +"<td width='8%'>"
                +"<div class='fl'>" 
                +"<img src='/DistributorSystem/"+data.photoHref+"' alt=''/>"        
                +"</div>"    
                +"</td>"
                +"<td width='40%'>"
                +"<div class='detail fl'>"    
                +"<p>"        
                +"<span>"+data.label+"</span>"            
                +"<span>"+data.code+"</span>"            
                +"</p>"        
                +"<p>"        
                +"<span>"+data.productName+"</span>"            
                +"<span class='fr'>"+data.specNameValue+"</span>"            
                +"</p>"        
                +"<p>"+data.standard+"</p>"     
                +"</div>"    
                +"</td>"
                +"<td width='8%'>"
                +"￥<span>"+data.orderedPrice+"</span>"    
                +"</td>"
                +"<td width='8%'>"
                +"<input type='text' value='"+data.MOQ+"'/><span>"+data.littleUnit
                +"</span>"
                +"</td>"
                +"<td width='8%'>￥<span>"+data.MOQ*data.orderedPrice+"</span></td>"
                +"<td width='20%' class='add'>"
                +"<p></p>"    
                +"</td>" 
                +"</tr>";
    			tbody.append(html);
    			calculate();
    			//添加订单商品
//    			var count=data.MOQ;
//    	        var price=Number(data.orderedPrice);
//    	        var productId=data.id;
//    	        var isactivity=0;
//    	        var activityId ="";
//    	        if(isactivity == 1){
//    	        	activityId = $(this).parent().parent().attr("data-isactivity");
//    	        }
//    	        var remark="";
//    	        var orderId = $('.order-number').attr('data-id');
//    	        var unit=data.littleUnit;
//    	        $.ajax({
//    	    		type:"GET",
//    	    		url:"/CustomerSystem/order/updateOrderProduct",
//    	    		data:{"order_info_id":orderId,
//    	    			"product_price_id":productId,
//    	    			"quantity":count,
//    	    			"price":price,
//    	    			"is_activity_product":isactivity,
//    	    			"product_activity_product_id":activityId,
//    	    			"unit":unit,
//    	    			"remark":remark},
//    	    		success:function(data){
//    	    			
//    	    		}
//    	    	});
    		}
    	});
    });
});
//数量金额相关blur
$('table').on('keyup','tbody tr td:nth-child(5) input',function(){
    var count=$(this).val();
    var price=Number($(this).parent().siblings('td:nth-child(4)').children('span').html());
    $(this).parent().siblings('td:nth-child(6)').children('span').html(count*price);
    calculate();
    //修改商品数量
    var productId=$(this).parent().parent().attr("data-id");
    var isactivity=$(this).parent().parent().attr("data-isactivity");
    var activityId ="";
    if(isactivity == 1){
    	activityId = $(this).parent().parent().attr("data-isactivity");
    }
    var remark=$(this).parent().siblings('td:nth-child(7)').children('p').html();
    var orderId = $('.order-number').attr('data-id');
    var unit=$(this).siblings('span').html()
//	$.ajax({
//		type:"POST",
//		url:"/CustomerSystem/order/updateOrderProduct",
//		data:{"order_info_id":orderId,
//			"product_price_id":productId,
//			"quantity":count,
//			"price":price,
//			"is_activity_product":isactivity,
//			"product_activity_product_id":activityId,
//			"unit":unit,
//			"remark":remark},
//		success:function(data){
//			
//		}
//	});
});
function calculate(){
    var total=0;
    var count=0;
    var tr=$('.product-list table tbody tr');
    tr.each(function(){
        count++;
       total += Number($(this).children('td:nth-child(6)').children('span').html());
    });
    $('.settle-accounts').children('.price').children('p:nth-child(1),p:nth-child(3)').children('span').children('span').html(total);
    $('.speical-price').children('p:nth-child(1)').children('span').html(count);
}
calculate();
$(".select ul").on('click','li',function(){
    $(this).parent().siblings('input').val($(this).html());
    $(this).parent().siblings('input.hidden').val($(this).attr('data-id'));
});
$(".select input").click(function(e){
    e.stopPropagation();
    var div=$(this);
    div.siblings('ul').toggleClass('hide');
    $(document).click(function() {
        if (!div.siblings('ul').hasClass("hide")) {
            div.siblings('ul').addClass("hide");
        }
    });
});
//提交订单
$('.fix-btn .submit').click(function(e){
	e.preventDefault();
	var orderInfo={};
	var product=[];
	orderInfo.invoicetype=$('.bill').find('input:radio[name="state"]:checked').val();
	orderInfo.deliveryDate=$('.date').children('input').val();
	orderInfo.remark=$('.remark').children('p').children('input').val();
	orderInfo.amount=$('.settle-accounts').children('.price').children('p:nth-child(1)').children('span').children('span').html();
	orderInfo.specialApprovalAmount=$('.settle-accounts').children('.price').children('p:nth-child(2)').children('span').children('span').html();
	if(orderInfo.specialApprovalAmount==""){
		orderInfo.isSpecialApproval=0;
	}else{
		orderInfo.isSpecialApproval=1;
	}
	$($('.product-list tbody tr')).each(function(){
		var orderContainProduct={};
		orderContainProduct.productPriceId=$(this).attr('data-id');
		orderContainProduct.quantity=Number($(this).children('td:nth-child(5)').children('input').val());
		orderContainProduct.price=Number($(this).children('td:nth-child(4)').children('span').html());
		orderContainProduct.unit=$(this).children('td:nth-child(5)').text();
		orderContainProduct.remark=$(this).children('td:nth-child(7)').children('p').html();
		product.push(orderContainProduct);
	})
	console.log(orderInfo,product)
	
	var products = JSON.stringify(product);
    var orderInfos =  JSON.stringify(orderInfo);
    var json = {"products":products,
		    "orderInfo":orderInfos};
    
    $.ajax({
		type:'post',
		url:'/DistributorSystem/order/insertOrderInfo',
		data:json,
		dataType : 'json' ,
		success:function(data){
			console.log(data);
			alert("保存成功")
		},
		error:function(){
			alert("保存失败")
		}
	});
	
//	$.ajax({
//        url:"/CustomerSystem/material/materialAdd",
//        data:{
//        "returnOrderList":returnOrderList   
//        },
//        type:'post',
//        dataType:"json",
//        success:function(data){
//        	window.location.href="/CustomerSystem/material/materialList"; 
//        }
//	});
});